package com.googlecode.garbagecan.test.table;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

public class Table {

	private Header header;
	private List<Row> rows;

	public Table() {
		this.rows = new ArrayList<Row>();
	}
	
	public Table(Header header, List<Row> rows) {
		this.header = header;
		this.rows = rows;
	}

	public Table setHeader(Header header) {
		this.header = header;
		return this;
	}
	
	public Table addRow(Row row) {
		this.rows.add(row);
		return this;
	}
	
	public String toString() {
		int[] maxLength = new int[this.header.getValues().length];

		Object[] headerValues = this.header.getValues();
		int length = headerValues.length;
		for (int i = 0; i < length; i++ ) {
			String value = (headerValues[i] == null) ? "" : headerValues[i].toString();
			if (value.length() > maxLength[i]) {
				maxLength[i] = value.length();
			}
		}

		for (Row row : rows) {
			Object[] rowValues = row.getValues();
			for (int i = 0; i < length; i++ ) {
				String value = (rowValues[i] == null) ? "" : rowValues[i].toString();
				if (value.length() > maxLength[i]) {
					maxLength[i] = value.length();
				}
			}
		}
		
		for (int i = 0; i < length; i++) {
			maxLength[i] += 4;
		}
		
		StringBuilder sb = new StringBuilder();
		
		for (int i = 0; i< length; i++) {
			String value = (headerValues[i] == null) ? "" : headerValues[i].toString();
			if (i == 0) {
				sb.append(StringUtils.rightPad(value, maxLength[i]));
			} else {
				sb.append(StringUtils.leftPad(value, maxLength[i]));
			}
		}
		sb.append("\n");
		
		for (Row row : rows) {
			Object[] rowValues = row.getValues();
			for (int i = 0; i < length; i++ ) {
				String value = (rowValues[i] == null) ? "" : rowValues[i].toString();
				if (i == 0) {
					sb.append(StringUtils.rightPad(value, maxLength[i]));
				} else {
					sb.append(StringUtils.leftPad(value, maxLength[i]));
				}
			}
			sb.append("\n");
		}
		
		return sb.toString();
	}

	public static void main(String[] args) {
		Header header = new Header(new Object[]{"header1", "header11", "header111"});
		List<Row> rows = new ArrayList<Row>();
		rows.add(new Row(new Object[] {"content1---", "content11", "content111"}));
		rows.add(new Row(new Object[] {"content2---", "content22", "content222"}));
		rows.add(new Row(new Object[] {"content3---", "content33", "content333"}));
		Table table = new Table(header, rows);
		System.out.println(table);
		
		table = new Table();
		table.setHeader(new Header(new Object[]{"header1", "header11", "header111"}));
		table.addRow(new Row(new Object[] {"content1---", "content11", "content111"}));
		table.addRow(new Row(new Object[] {"content2---", "content22", "content222"}));
		table.addRow(new Row(new Object[] {"content3---", "content33", "content333"}));
		System.out.println(table);
	}

}
